<template>
  <view class="register-container">
    <!-- 背景装饰 -->
    <view class="bg-decoration">
      <view class="circle circle-1"></view>
      <view class="circle circle-2"></view>
      <view class="circle circle-3"></view>
    </view>

    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-back" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <text class="nav-title">账号注册</text>
      <view class="nav-placeholder"></view>
    </view>

    <!-- 主要内容 -->
    <view class="register-content">
      <!-- Logo区域 -->
      <view class="logo-section">
        <image class="logo" src="/static/logo.png" mode="aspectFit"></image>
        <text class="app-name">创建新账号</text>
        <text class="app-desc">请填写以下信息完成注册</text>
      </view>

      <!-- 注册表单 -->
      <view class="register-form">
        <!-- 用户名输入 -->
        <!-- <view class="input-group">
          <view class="input-icon">
            <text class="iconfont icon-user">👤</text>
          </view>
          <input
            class="input-field"
            type="text"
            placeholder="请输入用户名"
            v-model="formData.username"
            @input="clearError('username')"
            :class="{ 'input-error': errors.username }"
          />
        </view>
        <text v-if="errors.username" class="error-text">{{
          errors.username
        }}</text> -->

        <!-- 手机号输入 -->
        <view class="input-group">
          <view class="input-icon">
            <text class="iconfont icon-phone">📱</text>
          </view>
          <input
            class="input-field"
            type="number"
            placeholder="请输入手机号"
            v-model="formData.phone"
            @input="clearError('phone')"
            :class="{ 'input-error': errors.phone }"
          />
        </view>
        <text v-if="errors.phone" class="error-text">{{ errors.phone }}</text>

        <!-- 密码输入 -->
        <view class="input-group">
          <view class="input-icon">
            <text class="iconfont icon-lock">🔒</text>
          </view>
          <input
            class="input-field"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请设置密码"
            v-model="formData.password"
            @input="clearError('password')"
            :class="{ 'input-error': errors.password }"
          />
          <view class="password-toggle" @click="togglePassword">
            <text class="toggle-icon">{{ showPassword ? "👁️" : "👁️‍🗨️" }}</text>
          </view>
        </view>
        <text v-if="errors.password" class="error-text">{{
          errors.password
        }}</text>

        <!-- 确认密码输入 -->
        <view class="input-group">
          <view class="input-icon">
            <text class="iconfont icon-lock">🔐</text>
          </view>
          <input
            class="input-field"
            :type="showConfirmPassword ? 'text' : 'password'"
            placeholder="请确认密码"
            v-model="formData.confirmPassword"
            @input="clearError('confirmPassword')"
            :class="{ 'input-error': errors.confirmPassword }"
          />
          <view class="password-toggle" @click="toggleConfirmPassword">
            <text class="toggle-icon">{{
              showConfirmPassword ? "👁️" : "👁️‍🗨️"
            }}</text>
          </view>
        </view>
        <text v-if="errors.confirmPassword" class="error-text">{{
          errors.confirmPassword
        }}</text>

        <!-- 协议同意 -->
        <view class="agreement-section">
          <view class="agreement-check" @click="toggleAgreement">
            <view class="checkbox" :class="{ checked: agreeTerms }">
              <text v-if="agreeTerms" class="check-icon">✓</text>
            </view>
            <text class="agreement-text">
              我已阅读并同意
              <text class="agreement-link" @click.stop="showUserAgreement"
                >《用户协议》</text
              >
              和
              <text class="agreement-link" @click.stop="showPrivacyPolicy"
                >《隐私政策》</text
              >
            </text>
          </view>
        </view>

        <!-- 注册按钮 -->
        <button
          class="register-btn"
          :class="{ 'btn-loading': isLoading, 'btn-disabled': !canSubmit }"
          :disabled="!canSubmit || isLoading"
          @click="handleRegister"
        >
          <text v-if="isLoading" class="loading-icon">⏳</text>
          <text class="btn-text">{{
            isLoading ? "注册中..." : "立即注册"
          }}</text>
        </button>

        <!-- 登录链接 -->
        <view class="login-link">
          <text class="login-text">已有账号？</text>
          <text class="login-btn" @click="goToLogin">立即登录</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onBeforeUnmount } from "vue";
import request from "@/api/request.js";
// 响应式数据
const formData = reactive({
  phone: "",
  verifyCode: "",
  password: "",
  confirmPassword: "",
  inviteCode: "",
});

const errors = reactive({
  phone: "",
  verifyCode: "",
  password: "",
  confirmPassword: "",
});

const showPassword = ref(false);
const showConfirmPassword = ref(false);
const agreeTerms = ref(false);
const isLoading = ref(false);
const codeDisabled = ref(false);
const countdown = ref(0);
const timer = ref(null);

// 计算属性
const canSubmit = computed(() => {
  return (
    formData.phone.trim() &&
    formData.password.trim() &&
    formData.confirmPassword.trim() &&
    agreeTerms.value &&
    !hasErrors.value
  );
});

const hasErrors = computed(() => {
  return Object.values(errors).some((error) => error);
});

// 生命周期
onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
});

// 方法
const goBack = () => {
  uni.navigateBack();
};

// 添加清除错误信息的方法
const clearError = (field) => {
  if (errors[field]) {
    errors[field] = "";
  }
};

const validateForm = () => {
  // 重置错误信息
  Object.keys(errors).forEach((key) => {
    errors[key] = "";
  });
  // // 用户名验证
  // if (!formData.username.trim()) {
  //   errors.username = "请输入用户名";
  //   return false;
  // }
  // if (formData.username.length < 1 || formData.username.length > 20) {
  //   errors.username = "用户名长度为1-20个字符";
  //   return false;
  // }
  // if (!/^[a-zA-Z0-9_\u4e00-\u9fa5]+$/.test(formData.username)) {
  //   errors.username = "用户名只能包含字母、数字、下划线和中文";
  //   return false;
  // }

  // 手机号验证
  if (!formData.phone.trim()) {
    errors.phone = "请输入手机号";
    return false;
  }
  if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
    errors.phone = "请输入正确的手机号";
    return false;
  }

  // 密码验证
  if (!formData.password.trim()) {
    errors.password = "请设置密码";
    return false;
  }
  if (formData.password.length < 6 || formData.password.length > 20) {
    errors.password = "密码长度为6-20个字符";
    return false;
  }
  // if (
  //   !/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/.test(formData.password)
  // ) {
  //   errors.password = "密码必须包含字母和数字";
  //   return false;
  // }

  // 确认密码验证
  if (!formData.confirmPassword.trim()) {
    errors.confirmPassword = "请确认密码";
    return false;
  }
  if (formData.password !== formData.confirmPassword) {
    errors.confirmPassword = "两次输入的密码不一致";
    return false;
  }

  return true;
};

const togglePassword = () => {
  showPassword.value = !showPassword.value;
};

const toggleConfirmPassword = () => {
  showConfirmPassword.value = !showConfirmPassword.value;
};

const toggleAgreement = () => {
  agreeTerms.value = !agreeTerms.value;
};

const sendVerifyCode = async () => {
  if (!formData.phone.trim()) {
    uni.showToast({
      title: "请先输入手机号",
      icon: "none",
    });
    return;
  }

  if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
    uni.showToast({
      title: "请输入正确的手机号",
      icon: "none",
    });
    return;
  }

  try {
    // 模拟发送验证码API
    await sendCodeAPI();

    uni.showToast({
      title: "验证码已发送",
      icon: "success",
    });

    // 开始倒计时
    startCountdown();
  } catch (error) {
    uni.showToast({
      title: error.message || "发送失败",
      icon: "none",
    });
  }
};

const startCountdown = () => {
  countdown.value = 60;
  codeDisabled.value = true;

  timer.value = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer.value);
      codeDisabled.value = false;
    }
  }, 1000);
};

const sendCodeAPI = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 模拟API调用
      resolve({ success: true });
    }, 1000);
  });
};

const handleRegister = async () => {
  if (!validateForm()) {
    return;
  }

  if (!agreeTerms.value) {
    uni.showToast({
      title: "请先同意用户协议和隐私政策",
      icon: "none",
    });
    return;
  }

  isLoading.value = true;
  toRegister();
};

const toRegister = async () => {
  try {
    let res = await request.post("/api/auth/register", {
      password: formData.password,
      phone: formData.phone,
    });
    console.log(res);
    if (res) {
      uni.showToast({
        title: "注册成功",
        icon: "success",
      });
      // 注册成功后，跳转到登录页面
      uni.redirectTo({
        url: "/pages/login/index",
      });
    } else {
      uni.showToast({
        title: res.message || "注册失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error('注册错误:', error);
    isLoading.value = false;
  } finally {
    isLoading.value = false;
  }
};

const goToLogin = () => {
  uni.redirectTo({
    url: "/pages/login/index",
  });
};

const showUserAgreement = () => {
  uni.navigateTo({
    url: "/pages/login/agreement",
  });
};

const showPrivacyPolicy = () => {
  uni.navigateTo({
    url: "/pages/login/privacyPolicy",
  });
};
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
  overflow: hidden;
}

/* 背景装饰 */
.bg-decoration {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  animation: float 8s ease-in-out infinite;
}

.circle-1 {
  width: 150rpx;
  height: 150rpx;
  top: 15%;
  left: -30rpx;
  animation-delay: 0s;
}

.circle-2 {
  width: 100rpx;
  height: 100rpx;
  top: 70%;
  right: -20rpx;
  animation-delay: 3s;
}

.circle-3 {
  width: 80rpx;
  height: 80rpx;
  top: 40%;
  right: 25%;
  animation-delay: 6s;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
    opacity: 0.3;
  }
  50% {
    transform: translateY(-15px) rotate(180deg);
    opacity: 0.6;
  }
}

/* 顶部导航 */
.nav-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  padding-top: calc(var(--status-bar-height) + 20rpx);
  position: relative;
  z-index: 10;
}

.nav-back {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  cursor: pointer;
}

.back-icon {
  font-size: 32rpx;
  color: #2c3e50;
  font-weight: bold;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #2c3e50;
}

.nav-placeholder {
  width: 60rpx;
}

/* 主要内容 */
.register-content {
  padding: 40rpx 60rpx 60rpx;
  position: relative;
  z-index: 1;
}

/* Logo区域 */
.logo-section {
  text-align: center;
  margin-bottom: 60rpx;
}

.logo {
  width: 100rpx;
  height: 100rpx;
  margin-bottom: 20rpx;
}

.app-name {
  display: block;
  font-size: 40rpx;
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 16rpx;
}

.app-desc {
  display: block;
  font-size: 26rpx;
  color: #fff;
}

/* 注册表单 */
.register-form {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20rpx;
  padding: 50rpx 40rpx;
  backdrop-filter: blur(10px);
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.08);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
}

/* 输入组 */
.input-group {
  position: relative;
  margin-bottom: 35rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  border: 2rpx solid #e5e5e5;
  transition: all 0.3s ease;
}

.input-group:focus-within {
   border-color: #667eea;
  background: #ffffff;
  box-shadow: 0 0 0 6rpx rgba(102, 126, 234, 0.1);
}

.input-icon {
  position: absolute;
  left: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 28rpx;
  color: #95a5a6;
  z-index: 2;
}

.input-field {
  width: 100%;
  height: 80rpx;
  padding: 0 120rpx 0 65rpx;
  border: none;
  background: transparent;
  font-size: 30rpx;
  color: #2c3e50;
}

.input-field::placeholder {
  color: #bdc3c7;
}

.input-error {
  border-color: #e74c3c !important;
}

.password-toggle {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
  cursor: pointer;
}

.toggle-icon {
  font-size: 28rpx;
  color: #95a5a6;
}

/* 验证码组 */
.code-group {
  display: flex;
  align-items: center;
}

.code-input {
  padding-right: 200rpx !important;
}

.code-btn {
  position: absolute;
  right: 10rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 180rpx;
  height: 60rpx;
  background: linear-gradient(135deg, #667eea 0%, #2980b9 100%);
  color: #ffffff;
  border: none;
  border-radius: 8rpx;
  font-size: 24rpx;
  cursor: pointer;
  transition: all 0.3s ease;
}

.code-btn.btn-disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.error-text {
  color: #e74c3c;
  font-size: 22rpx;
  margin-top: -25rpx;
  margin-bottom: 15rpx;
  margin-left: 20rpx;
}

/* 协议部分 */
.agreement-section {
  margin-bottom: 40rpx;
}

.agreement-check {
  display: flex;
  align-items: flex-start;
  cursor: pointer;
}

.checkbox {
  width: 30rpx;
  height: 30rpx;
  border: 2rpx solid #bdc3c7;
  border-radius: 6rpx;
  margin-right: 16rpx;
  margin-top: 4rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  flex-shrink: 0;
}

.checkbox.checked {
  background: #667eea;
  border-color: #667eea;
}

.check-icon {
  color: #ffffff;
  font-size: 18rpx;
  font-weight: bold;
}

.agreement-text {
  font-size: 24rpx;
  color: #7f8c8d;
  line-height: 1.5;
}

.agreement-link {
  color: #667eea;
  /* text-decoration: underline; */
}

/* 注册按钮 */
.register-btn {
  width: 100%;
  height: 80rpx;
  background: linear-gradient(135deg, #667eea 0%, #2980b9 100%);
  border: none;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30rpx;
  transition: all 0.3s ease;
  box-shadow: 0 6rpx 20rpx rgba(52, 152, 219, 0.3);
}

.register-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 3rpx 10rpx rgba(52, 152, 219, 0.3);
}

.btn-disabled {
  background: #bdc3c7 !important;
  box-shadow: none !important;
}

.btn-loading {
  background: #95a5a6 !important;
}

.loading-icon {
  margin-right: 16rpx;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.btn-text {
  font-size: 30rpx;
  color: #ffffff;
  font-weight: bold;
}

/* 登录链接 */
.login-link {
  text-align: center;
}

.login-text {
  font-size: 26rpx;
  color: #7f8c8d;
}

.login-btn {
  font-size: 26rpx;
  color: #667eea;
  margin-left: 10rpx;
  cursor: pointer;
}
</style>
